document.addEventListener('DOMContentLoaded', function() {
    const profileForm = document.getElementById('profileForm');
    const saveBtn = document.getElementById('saveBtn');

    setupPasswordToggle('toggleCurrentPassword', 'currentPasswordIcon');
    setupPasswordToggle('toggleNewPassword', 'newPasswordIcon');
    setupPasswordToggle('toggleConfirmPassword', 'confirmPasswordIcon');

    saveBtn.addEventListener('click', function(event) {
        event.preventDefault();
        if (validateForm()) {
            saveProfileChanges();
        }
    });

    // 密码显示/隐藏切换函数
    function setupPasswordToggle(toggleId, iconId) {
        const toggleBtn = document.getElementById(toggleId);
        const icon = document.getElementById(iconId);

        if (toggleBtn && icon) {
            toggleBtn.addEventListener('click', function() {
                const passwordInput = toggleBtn.parentElement.querySelector('input');
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                } else {
                    passwordInput.type = 'password';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                }
            });
        }
    }

    // 表单验证函数（修正：移除对email的验证，因为HTML中没有该字段）
    function validateForm() {
        let isValid = true;
        console.log('开始表单验证...');

        // 获取元素并检查是否存在
        const telephoneInput = document.getElementById('telephone');
        const newPasswordInput = document.getElementById('new_password');
        const confirmPasswordInput = document.getElementById('confirm_password');

        // 验证电话号码
        if (telephoneInput && telephoneInput.value.trim()) {
            if (!isValidTelephone(telephoneInput.value.trim())) {
                showError('telephone', '请输入有效的11位手机号码');
                isValid = false;
            } else {
                hideError('telephone');
            }
        }

        // 验证密码
        if (newPasswordInput && confirmPasswordInput) {
            const newPassword = newPasswordInput.value;
            const confirmPassword = confirmPasswordInput.value;

            if (newPassword || confirmPassword) {
                if (newPassword !== confirmPassword) {
                    showError('confirm_password', '两次输入的密码不一致');
                    isValid = false;
                } else {
                    hideError('confirm_password');
                }

                if (newPassword.length < 6) {
                    showError('new_password', '密码长度至少为6位');
                    isValid = false;
                } else {
                    hideError('new_password');
                }

                const currentPasswordInput = document.getElementById('current_password');
                if (currentPasswordInput && newPassword && !currentPasswordInput.value) {
                    showError('current_password', '请输入当前密码');
                    isValid = false;
                } else {
                    hideError('current_password');
                }
            }
        }

        console.log('表单验证结果:', isValid);
        return isValid;
    }

    // 邮箱验证辅助函数（保留，但在验证中不使用）
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // 电话号码验证辅助函数
    function isValidTelephone(telephone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(telephone);
    }

    // 显示错误信息
    function showError(fieldId, message) {
        const errorElement = document.getElementById(`${fieldId}Error`);
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');
        }

        const inputElement = document.getElementById(fieldId);
        if (inputElement) {
            inputElement.classList.add('border-red-500');
            inputElement.classList.remove('focus:border-blue-500');
            inputElement.classList.add('focus:border-red-500');
        }
    }

    // 隐藏错误信息
    function hideError(fieldId) {
        const errorElement = document.getElementById(`${fieldId}Error`);
        if (errorElement) {
            errorElement.classList.add('hidden');
        }

        const inputElement = document.getElementById(fieldId);
        if (inputElement) {
            inputElement.classList.remove('border-red-500');
            inputElement.classList.add('focus:border-blue-500');
            inputElement.classList.remove('focus:border-red-500');
        }
    }

    // 保存个人资料修改
    function saveProfileChanges() {
        const formData = {
            // 移除email字段，因为HTML中没有
            telephone: document.getElementById('telephone').value,
            age: document.getElementById('age').value,
            gender: document.getElementById('gender').value,
            class_id: document.getElementById('class_id').value,
            major: document.getElementById('major').value,
            address: document.getElementById('address').value,
            current_password: document.getElementById('current_password').value,
            new_password: document.getElementById('new_password').value
        };

        console.log('准备发送数据:', formData);

        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

        fetch('/student/message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrf_token')
            },
            body: JSON.stringify(formData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('API响应:', data);

            if (data.success) {
                showToast('success', data.message || '个人资料更新成功！');
                document.getElementById('current_password').value = '';
                document.getElementById('new_password').value = '';
                document.getElementById('confirm_password').value = '';

                setTimeout(() => {
                    window.location.href = "/student";
                }, 2000);
            } else {
                if (data.errors) {
                    Object.keys(data.errors).forEach(field => {
                        showError(field, data.errors[field]);
                    });
                }
                showToast('error', data.message || '更新失败，请重试');
            }
        })
        .catch(error => {
            console.error('请求错误:', error);
            showToast('error', '网络错误，请稍后再试');
        })
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fa fa-save mr-2"></i> 保存更改';
        });
    }

    // Toast提示组件
    function showToast(type, message, duration = 3000) {
        let toastContainer = document.getElementById('toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.className = 'fixed top-4 right-4 z-50 flex flex-col gap-3 w-80 max-w-sm';
            document.body.appendChild(toastContainer);
        }

        const toast = document.createElement('div');
        toast.className = `toast-item bg-white shadow-lg rounded-lg p-4 border-l-4 transition-all duration-300 transform translate-x-full opacity-0 flex items-start gap-3 ${
            type === 'success' ? 'border-green-500' : 'border-red-500'
        }`;

        const iconClass = type === 'success' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500';
        const bgColor = type === 'success' ? 'bg-green-100' : 'bg-red-100';

        toast.innerHTML = `
            <div class="${bgColor} p-2 rounded-full">
                <i class="fa ${iconClass}"></i>
            </div>
            <div class="flex-1">
                <p class="font-medium text-gray-800">${type === 'success' ? '成功' : '错误'}</p>
                <p class="text-sm text-gray-600 mt-1">${message}</p>
            </div>
            <button class="text-gray-400 hover:text-gray-600 ml-2" onclick="this.parentElement.remove()">
                <i class="fa fa-times"></i>
            </button>
        `;

        toastContainer.appendChild(toast);

        setTimeout(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        }, 10);

        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => {
                if (toastContainer.contains(toast)) {
                    toastContainer.removeChild(toast);
                    if (toastContainer.children.length === 0) {
                        document.body.removeChild(toastContainer);
                    }
                }
            }, 300);
        }, duration);
    }

    // 获取CSRF令牌
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});